package core

import (
	"gateway/config"
	"net"
	"share/app"
	"share/msg"
	"util/log"
)

var (
	gate = &Gate{}
)

type Gate struct {
	appClient *app.AppClient
	servSock  *ServSock
	mquit     chan bool
	cfg       *config.Config
	runchan   chan bool
	router    *route
}

func (g *Gate) Start(c *config.Config, ch chan bool) {
	g.cfg = c
	g.mquit = ch
	g.runchan = make(chan bool)
	g.initAll()
	g.run()
}

func (g *Gate) initAll() {
	g.appClient = app.CreateAppClient()
	g.servSock = CreateServSock(g.cfg.ServIp, g.cfg.ServPort)
	g.router = createRoute()
}

func (g *Gate) run() {

	if err := g.servSock.Start(4); err != nil {
		panic("serv sock failed")
	}

	addr, _ := g.servSock.Addr().(*net.TCPAddr)

	g.appClient.Run(g.cfg.CenterIp, g.cfg.CenterPort, msg.AT_GATE, addr.IP.String(), addr.Port)
	g.router.Start()
	log.TraceInfo("Gate", "service start")

loop:
	for {
		select {
		case <-g.runchan:
			break loop
		}
	}

	g.appClient.Shutdown()

	g.mquit <- true
}

func (g *Gate) shutdown() {
	g.runchan <- true
}

func GetGate() *Gate {
	return gate
}

func ServiceQuit() {
	gate.shutdown()
}
